#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>


#define DATASIZE  94
#define COUNT 100

int main(void)
{
	int fd;
	int i, j;
	unsigned long len;

	char *data = (char*)malloc(DATASIZE + 1);
	if (!data) {
		printf("malloc err! %m\n");
		exit(-1);
	}
	memset(data, 0, sizeof(char ) * DATASIZE + 1);

	for (i = 0; i < DATASIZE; i++) {
		data[i] = (char)i + '!';
	}
	
	fd = open("/dev/scull0", O_WRONLY);
	if (fd == -1) {
		printf("open err! %m\n");
		exit(-1);
	}

	printf("open success! fd = %d\n", fd);

	for (i = 0; i < COUNT; i++) {
		len = write(fd, data, DATASIZE);
		if (len == -1) {
			printf("write err! %m\n");
		} else {
			printf("scull_app: write len = %ld\n", len);		
		}
	}

	close(fd);
	
	fd = open("/dev/scull0", O_RDONLY);
	if (fd == -1) {
		printf("open err! %m\n");
		exit(-1);
	}
	printf("open success! fd = %d\n", fd);

	for (i = 0; i < DATASIZE; i++) {
		memset(data, 0, sizeof(char ) * DATASIZE + 1);
		len = 0;
		len = read(fd, data, DATASIZE - i);
		if (len == -1) {
			printf("read err! %m\n");
		} else {
			printf("scull_app: read[%d] len = %ld\ndata = ", i + 1, len);
			for (j = 0; j < DATASIZE; j++)
				printf("%c", data[j]);
			printf("\n");
		}
	}

	close(fd);
	
	return 0;
}
